import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';

import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import {  Button, Card, Col, Drawer, Modal, Row, Space, message } from 'antd';
import React, { useRef, useState } from 'react';

import CreateModal from '@/pages/TableList/components/CreateModal';
import UpdateModal from '@/pages/TableList/components/UpdateModal';
import {
  addInterfaceInfoUsingPost,
  deleteInterfaceInfoUsingPost,
  listInterfaceInfoByPageUsingGet,
  offlineInterfaceInfoUsingPost,
  onlineInterfaceInfoUsingPost,
  updateInterfaceInfoUsingPost,
} from '@/services/openAPI-backend/interfaceInfoController';
// @ts-ignore
import type { SortOrder } from 'antd/lib/table/interface';
import {keyframes} from "antd-style";
const { confirm } = Modal;
interface DescriptionItemProps {
  title: string;
  content: React.ReactNode;
}
const DescriptionItem = ({ title, content }: DescriptionItemProps) => (
  <div
    className="site-description-item-profile-wrapper"
    style={{
      display: 'flex',
      marginBottom: 12,
      marginTop: 5,
      fontSize: 20,
    }}
  >
    {title}:
    <p
      style={{
        color: '#ad2102',
        marginLeft: 8,
        fontSize: 20,
      }}
    >
      {' '}
      {content}
    </p>
  </div>
);
const TableList: React.FC = () => {
  const [Draweropen, setDrawerOpen] = useState(false);
  const onClose = () => {
    setDrawerOpen(false);
  };
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  //  const deleteModalOpen = useState<boolean>(false)
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [DrawerData, setDrawerData] = useState<API.InterfaceInfo>();
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfo>();
  const [selectedRowsState, setSelectedRows] = useState<API.InterfaceInfo[]>([]);
  const showDrawer = (values: API.interfaceInfo) => {
    setDrawerOpen(true);
    setDrawerData(values);
  };
  const handleAdd = async (fields: API.InterfaceInfo) => {
    const hide = message.loading('正在添加');
    try {
      await addInterfaceInfoUsingPost({ ...fields });
      hide();
      message.success('Added successfully');
      handleModalOpen(false);
      message.success('Added successfully and will refresh soon');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('Adding failed, please try again!');
      return false;
    }
  };
  const handleUpdate = async (fields: API.InterfaceInfo) => {
    if (!currentRow) {
      return;
    }
    const hide = message.loading('Updating');
    try {
      await updateInterfaceInfoUsingPost({
        id: currentRow.id,
        ...fields,
      });
      hide();
      message.success('Updated is successful');
      message.success('Updated successfully and will refresh soon');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('Updated failed, please try again!');
      return false;
    }
  };
  const handleRemove = async (record: API.InterfaceInfo) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      await deleteInterfaceInfoUsingPost({
        id: record.id,
      });
      hide();
      message.success('Deleted successfully and will refresh soon');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('Delete failed, maybe something wrong');
      return false;
    }
  };
  const handleOnline = async (record: API.InterfaceInfo) => {
    const hide = message.loading('正在发布');
    if (!record) return true;
    if (record.status === 1) {
      message.warning('接口已经上线，请检查接口状态');
      return false;
    }
    try {
      await onlineInterfaceInfoUsingPost({
        id: record.id,
      });
      hide();
      message.success('接口成功发布');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('发布失败，请重试');
      return false;
    }
  };
  const handleOffline = async (record: API.InterfaceInfo) => {
    const hide = message.loading('下线中');
    if (!record) return true;
    if (record.status === 0) {
      message.warning('接口已经下线，请检查接口状态');
      return false;
    }
    try {
      await offlineInterfaceInfoUsingPost({
        id: record.id,
      });
      hide();
      message.success('接口下线成功，请重新部署');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('下线失败，请重试');
      return false;
    }
  };
  const showDeleteConfirm = (value: API.InterfaceInfo) => {
    const recordvalue = value;
    // @ts-ignore
    confirm({
      title: '是否要删除',
      content: '删除后需要重新部署接口',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      open: true,
      onOk() {
        handleRemove(recordvalue);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const showOnlineConfirm = (value: API.InterfaceInfo) => {
    if(value.status === 1){
      message.info('接口已经上线，请检查接口状态');
      return false;
    }
    if(value.status === 2){
      message.warning('接口还未通过审核，审核通过后您方可发布');
      return false;
    }
    const recordvalue = value;
    // @ts-ignore
    confirm({
      title: '是否要发布该接口',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      open: true,
      onOk() {
        handleOnline(recordvalue);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const showOfflineConfirm = (value: API.InterfaceInfo) => {
    if(value.status === 0){
      message.warning('接口已经下线，请检查接口状态');
      return false;
    }
    if(value.status === 2){
      message.warning('接口还未通过审核，审核通过后您方可发布');
      return false;
    }
    const recordvalue = value;
    // @ts-ignore
    confirm({
      title: '是否要下线该接口',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      open: true,
      onOk() {
        handleOffline(recordvalue);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const simpleColumns: ProColumns<API.InterfaceInfo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
    },
    {
      title: '接口名称',
      dataIndex: 'name',
      tip: 'The rule name is the unique key',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '来将可留下姓名',
          },
        ],
      },
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '我咋去找你啊',
          },
        ],
      },
    },
    {
      title: '接口地址',
      dataIndex: 'url',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '我去哪找你啊',
          },
        ],
      },
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" />,
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: (
            <FormattedMessage
              id="pages.searchTable.nameStatus.default"
              defaultMessage="Shut down"
            />
          ),
          status: 'Default',
        },
        1: {
          text: (
            <FormattedMessage id="pages.searchTable.nameStatus.running" defaultMessage="Running" />
          ),
          status: 'Processing',
        },2: {
          text: (
            <FormattedMessage id="ages.searchTable.nameStatus.abnormal" defaultMessage="审核中" />
          ),
          status: 'Warning',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.searchTable.config" defaultMessage="Configuration" />
        </a>,
        <a
          key="delete"
          onClick={() => {
            showDeleteConfirm(record);
          }}
        >
          <FormattedMessage
            id="pages.searchTable.subscribeAlert"
            defaultMessage="Subscribe to alerts"
          />
        </a>,
        <a
          key="status"
          onClick={() => {
            showOnlineConfirm(record);
          }}
        >
          <FormattedMessage id="1" defaultMessage="发布" />
        </a>,
        <a
          key="status"
          onClick={() => {
            showOfflineConfirm(record);
          }}
        >
          <FormattedMessage id="1" defaultMessage="下线" />
        </a>,

        <a
          key="checkout"
          onClick={() => {
            showDrawer(record);
          }}
        >
          <FormattedMessage id="1" defaultMessage="接口信息" />
        </a>,
      ],
    },
  ];
  const columns: ProColumns<API.InterfaceInfo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
    },
    {
      title: '接口名称',
      dataIndex: 'name',
      tip: 'The rule name is the unique key',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '来将可留下姓名',
          },
        ],
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: '费用',
      dataIndex: 'pointsCost',
      valueType: 'digit',

    },
    {
      title: '请求方法',
      dataIndex: 'method',
      valueType: 'text',
      key: 'method',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '我咋去找你啊',
          },
        ],
      },
      valueEnum: {
        'POST': {
          text: (
            <FormattedMessage
              id="POST"
              defaultMessage="POST"
            />
          ),
        },
        'GET': {
          text: (
            <FormattedMessage id="GET" defaultMessage="GET" />
          ),
        },
      },
    },
    {
      title: '接口网关(用户请求地址)',
      dataIndex: 'url',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '如无网关则与接口地址相同',
          },
        ],
      },
    },
    {
      title: '接口地址',
      dataIndex: 'relUrl',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此为必填项',
          },
        ],
      },
    },
    {
      title: '请求参数',
      dataIndex: 'requestParams',
      valueType: 'jsonCode',

    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      valueType: 'jsonCode',
      /* formItemProps:{
        rules:[{
          required:true,
          message:'为什么不完整？',
        }]
      }*/
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      valueType: 'jsonCode',
      /*formItemProps:{
        rules:[{
          required:true,
          message:'我怎么知道你啥意思',
        }]
      }*/
    },{
      title: '接口参数说明',
      dataIndex: 'remarks',
      valueType: 'textarea',
      /*formItemProps:{
        rules:[{
          required:true,
          message:'我怎么知道你啥意思',
        }]
      }*/
    },

    {
      title: <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" />,
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: (
            <FormattedMessage
              id="pages.searchTable.nameStatus.default"
              defaultMessage="Shut down"
            />
          ),
          status: 'Default',
        },
        1: {
          text: (
            <FormattedMessage id="pages.searchTable.nameStatus.running" defaultMessage="Running" />
          ),
          status: 'Warning',
        },
        2: {
          text: (
            <FormattedMessage id="pages.searchTable.nameStatus.default"
                              defaultMessage="Shut down" />
          ),
          status: 'Warning',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.searchTable.config" defaultMessage="Configuration" />
        </a>,
        <a
          key="delete"
          onClick={() => {
            showDeleteConfirm(record);
          }}
        >
          <FormattedMessage
            id="pages.searchTable.subscribeAlert"
            defaultMessage="Subscribe to alerts"
          />
        </a>,
        <a
          key="status"
          onClick={() => {
            showOnlineConfirm(record);
          }}
        >
          <FormattedMessage id="1" defaultMessage="发布" />
        </a>,
        <a
          key="status"
          onClick={() => {
            showOfflineConfirm(record);
          }}
        >
          <FormattedMessage id="1" defaultMessage="下线" />
        </a>,
      ],
    },
  ];
  const fadeIn = keyframes`
        from {
            opacity: 0;
            transform: translateX(50%); /* 初始位置在屏幕下方100% */
        }
        to {
            opacity: 1;
            transform: translateX(0); /* 结束位置在正常位置 */
        }
`;
  return (
    <PageContainer style={{animation: `${fadeIn} 0.5s ease-in-out`}}>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}

        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        request={async (
          params: U & {
            pageSize?: number;
            current?: number;
            keyword?: string;
          },
          sort: Record<string, SortOrder>,
          filter: Record<string, (string | number)[] | null>,
        ) => {
          const res: any = await listInterfaceInfoByPageUsingGet({
            ...params,
          });
          if (res?.data) {
            return {
              data: res?.data.records || [],
              success: true,
              total: res?.data.total || 0,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={simpleColumns}
        // rowSelection={{
        //   ...rowSelection
        // }}
      />
      {/*{selectedRowsState?.length > 0 && (*/}
      {/*  <FooterToolbar*/}
      {/*    extra={*/}
      {/*      <div>*/}
      {/*        已选择{' '}*/}
      {/*        <a*/}
      {/*          style={{*/}
      {/*            fontWeight: 600,*/}
      {/*          }}*/}
      {/*        >*/}
      {/*          {selectedRowsState.length}*/}
      {/*        </a>{' '}*/}
      {/*        项 &nbsp;&nbsp;*/}
      {/*      </div>*/}
      {/*    }*/}
      {/*  >*/}
      {/*    <Button*/}
      {/*      onClick={async () => {*/}
      {/*        await handleRemove(selectedRowsState);*/}
      {/*        setSelectedRows([]);*/}
      {/*        actionRef.current?.reloadAndRest?.();*/}
      {/*      }}*/}
      {/*    >*/}
      {/*      批量删除*/}
      {/*    </Button>*/}
      {/*    <Button type="primary">批量审批</Button>*/}
      {/*  </FooterToolbar>*/}
      {/*)}*/}
      {/*接口信息模块*/}
      <Drawer
          width={720}
          style={{fontSize: '16px'}}
          placement="right"
          closable={false}
          onClose={onClose}
          open={Draweropen}
          extra={<Space></Space>}
          size="default"
          keyboard={true}
      >
        <Card
            title={<p style={{fontSize: '24px',fontWeight: 'bold',marginTop: 20}}>接口详细信息</p>}
            style={{
              width: 580,
              marginBottom: 24,
              marginLeft: 5,
              borderRadius: 10,
              border: 0,
              justifyContent: 'space-between',
            }}
        >
          <Row >
            <Col span={12}>
              <DescriptionItem title="ID" content={DrawerData?.id}/>
            </Col>
            <Col span={12}>
              <DescriptionItem title="Name" content={DrawerData?.name} />
            </Col>
          </Row>
          <Row >
            <Col span={24}>
              <DescriptionItem title="描述" content={DrawerData?.description} style={{ whiteSpace: 'pre-wrap' }} />
            </Col>
          </Row>
          <Row>
            <Col span={500}>
              <p style={{ fontSize: "20px",display: 'inline-block'}}>网关：<a style={{color: '#ad2102', fontSize: "20px"}}>{DrawerData?.url}</a></p>
            </Col>
          </Row>
          <Row>
            <Col span={500}>
              <p style={{ fontSize: "20px",display: 'inline-block'}}>URL：<a style={{color: '#ad2102', fontSize: "20px"}}>{DrawerData?.relUrl}</a></p>
            </Col>
          </Row>
          <Row>
            <Col span={500}>
              <p style={{fontSize:"20px"}}>请求头：<a style={{color:'#ad2102',fontSize:"20px",whiteSpace: 'pre-wrap'}}>{DrawerData?.requestHeader}</a></p>

            </Col>
          </Row>
          <Row>
            <Col>
              <DescriptionItem title="响应头" content={DrawerData?.responseHeader} />
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <DescriptionItem
                  title="接口状态"
                  content={DrawerData?.status == 1 ? '已发布' : '已下线'}
              />
            </Col>
            <Col>
              <DescriptionItem title="请求方式" content={DrawerData?.method} />
            </Col>
          </Row>
          <Row>
            <Col>
              <DescriptionItem title="创建时间" content={DrawerData?.createTime} />
            </Col>
          </Row>
          <Row>
            <Col>
              <DescriptionItem title="更新时间" content={DrawerData?.updateTime} />
            </Col>
          </Row>
          <Row>
            <Col>
              <DescriptionItem title="请求参数" content={DrawerData?.requestParams} />
            </Col>
          </Row>
        </Card>
        <Space
            style={{
              display: 'flex',
              justifyContent: 'flex-end',
              alignItems: 'flex-end',
            }}
        >
          <Button onClick={onClose}>Cancel</Button>
          <Button type="primary" onClick={onClose}>
            OK
          </Button>
        </Space>
      </Drawer>
      {/*更新模块*/}
      <UpdateModal
        columns={columns}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        isOpen={updateModalOpen}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
      <CreateModal
        columns={columns}
        onCancel={() => {
          handleModalOpen(false);
        }}
        onSubmit={(values) => handleAdd(values)}
        isOpen={createModalOpen}
      />
    </PageContainer>
  );
};

export default TableList;
